package org.wq.config;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import tk.mybatis.spring.mapper.MapperScannerConfigurer;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * Created by admin on 2016/11/28.
 */
@Configuration
public class MyBatisConfig {


    // 创建数据源
    @Bean
    public DataSource dataSource(DataSourceProperties dataSourceProperties) throws Exception {

        Properties props = new Properties();
        props.put("driverClassName", dataSourceProperties.jdbc_driverClassName);
        props.put("url", dataSourceProperties.jdbc_url);
        props.put("username", dataSourceProperties.jdbc_username);
        props.put("password", dataSourceProperties.jdbc_password);
        return DruidDataSourceFactory.createDataSource(props);

    }

    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource,MyBatisProperties myBatisProperties,PageHelper pageHelper) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        // 设置分页插件
        sqlSessionFactoryBean.setPlugins(new Interceptor[]{pageHelper});
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setTypeAliasesPackage(myBatisProperties.mybatis_typeAliasesPackage);
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(myBatisProperties.mybatis_mapperLocations));
        return sqlSessionFactoryBean.getObject();
    }

    // 整合通用mapper
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
        mapperScannerConfigurer.setBasePackage("org.wq.mapper");
        return mapperScannerConfigurer;
    }


    // 集成分页插件
    @Bean
    public PageHelper pageHelper(DataSource dataSource) {
        PageHelper pageHelper = new PageHelper();
        Properties p = new Properties();
        p.setProperty("offsetAsPageNum", "true");
        p.setProperty("rowBoundsWithCount", "true");
        p.setProperty("reasonable", "true");
        pageHelper.setProperties(p);
        return pageHelper;
    }

}
